<template>
  <div class="work_order_expend_time">
    <one-title title="工单消耗工时统计" @refreshData="refresh"></one-title>
    <div class="task_tree_container fixed_top_56">
      <task-bom-tree ref="taskBomTree" @selectNode="selectNode"></task-bom-tree>
      <div class="task_tree_content">
        <mes-search-comp
          :searchList="tableColConfig"
          :searchResult="searchResult"
          @searchInfo="_info"
          ref="mesSearch">
        </mes-search-comp>
        <div class="table_container">
          <el-table
            ref="tableNode"
            :data="listData.list"
            border
            stripe
            v-loading="isLoading1"
            :row-class-name="({row}) => !selectData.some((item) => item.id === row.id) || 'line_selected'"
            @row-click="(row) => $refs.tableNode.toggleRowSelection(row)"
            @sort-change="_sort"
            @selection-change="handleSelectionChange"
            @filter-change="handleFilterChange">
            <el-table-column
              fixed="left"
              width="40"
              type="selection"
              align="center">
            </el-table-column>
            <mes-col-comp
              :key="index"
              v-for="(column, index) in columnList"
              :column="column">
            </mes-col-comp>
          </el-table>
        </div>
        <mes-pagination
          @updateData="init"
          :pageSelectShow="false"
          :currentPage="listData.pageNo"
          :total="listData.count || 0"
          :pageSize="listData.pageSize">
        </mes-pagination>
        <div class="table_container batch_list_detail" v-if="selectData.length >= 1">
          <el-table
            ref="nTableNode"
            :data="turnoverData.list"
            :max-height="tableCascadeHeight"
            border
            stripe
            style="width: 100%"
            @sort-change="_sort"
            v-loading="isLoading">
            <el-table-column
              fixed="left"
              prop="number"
              label="周转码"
              min-width="120"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              fixed="left"
              prop="turnoverProcessStatusLabel"
              label="周转进度"
              align="center"
              min-width="120">
              <template slot-scope="scope">
                <turnover-progress-status :data="scope.row"></turnover-progress-status>
              </template>
            </el-table-column>
            <el-table-column
              fixed="left"
              prop="turnoverStatus"
              label="周转状态"
              align="center"
              min-width="120">
              <template slot-scope="scope">
                <turnover-status :data="scope.row"></turnover-status>
              </template>
            </el-table-column>
            <el-table-column
              prop="productionQuantity"
              label="计划数量"
              align="center"
              width="100">
            </el-table-column>
            <el-table-column
              prop="practicalStartDate"
              label="实际开始时间"
              align="center"
              show-overflow-tooltip
              min-width="140">
              <template slot-scope="scope">{{scope.row.practicalStartDate | timeFormat('YYYY-MM-DD')}}</template>
            </el-table-column>
            <el-table-column
              prop="practicalEndDate"
              label="实际完成时间"
              align="center"
              show-overflow-tooltip
              min-width="140">
              <template slot-scope="scope">{{scope.row.practicalEndDate | timeFormat('YYYY-MM-DD')}}</template>
            </el-table-column>
            <el-table-column
              prop="currentWorkstageName"
              label="当前工序"
              align="center"
              min-width="120"
              show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="taskTypeLabel"
              label="任务类型"
              align="left"
              min-width="100"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <task-type :data="scope.row"></task-type>
              </template>
            </el-table-column>
            <el-table-column
              prop="estimateEffort"
              label="定额工时"
              align="center"
              fixed="right"
              width="100">
            </el-table-column>
            <el-table-column
              prop="expendTime"
              label="实际工时"
              align="center"
              fixed="right"
              :resizable="false"
              className="fontColor"
              min-width="80">
            </el-table-column>
          </el-table>
          <mes-pagination
            @updateData="turnoverList"
            :currentPage="turnoverData.pageNo"
            :total="turnoverData.count || 0"
            :pageSize="turnoverData.pageSize">
          </mes-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import tableColConfig from './tableColumns'
import {TurnoverStatus, TaskType, TurnoverProgressStatus} from '@/components/mesDict'

export default {
  name: 'WorkOrderExpendTime',
  components: {
    TurnoverStatus,
    TaskType,
    TurnoverProgressStatus,
  },
  data() {
    return {
      selectData: [], // 选择的列表
      searchResult: NaN, // 搜索结果数
      isLoading1: false, // 工单列表数据是否加载
      isLoading: false, // 周转批次列表数据是否加载
      searchData: {}, // 搜索列表数据
      sortData: {}, // 排序字段
      turnoverId: '', // 周转批次id
      taskNumber: '', // 当前树形taskNumber
      workorderIds: '', // 当前树形工单ids
    }
  },
  computed: {
    // 获取工单列表数据
    listData() {
      return this.$store.state.workOrderExpendTime.listData
    },
    // 获取周转批次列表数据
    turnoverData() {
      return this.$store.state.workOrderExpendTime.turnoverData
    },
    // 工单状态
    workorderStatus() {
      let workorderStatus = this.$store.state.dict.workorderStatus.labels || []
      return this.addLabelAll(workorderStatus)
    },
    // 工单类型
    workorderType() {
      let workorderType = this.$store.state.dict.workorderType.labels || []
      return this.addLabelAll(workorderType)
    },
    // 任务类别
    taskType() {
      let taskType = this.$store.state.dict.taskType.labels || []
      return this.addLabelAll(taskType)
    },
    // 周转批次任务类型
    turnoverTaskType() {
      return this.$store.state.dict.turnoverTaskType.labels || []
    },
    // 工单来源
    workorderSource() {
      let workorderSource = this.$store.state.dict.workorderSource.labels || []
      return this.addLabelAll(workorderSource)
    },
    // 工单进度
    workorderProcessStatus() {
      return this.$store.state.dict.workorderProcessStatus.labels || []
    },
    // 周转状态列表(工单状态为：部分拆分，拆分完成，已拆分)
    processStatus() {
      return this.workorderProcessStatus.filter(item => item.value !== 'ToBeAssigned' && item.value !== 'ToBeConfirmed' && item.value !== 'ToBeSplitted')
      // return list.length > 0 ? [{id: this.processStatusIds, label: '全部'}, ...list] : list
    },
    // 进度状态初始查询条件
    processStatusIds() {
      let ids = []
      this.workorderProcessStatus.map((item) => {
        if (item.value !== 'ToBeAssigned' && item.value !== 'ToBeConfirmed' && item.value !== 'ToBeSplitted') {
          ids.push(item.id)
        }
      })
      return ids.join(',')
    },
    tableColConfig,
    // 列循环
    columnList() {
      return this.tableColConfig.filter(item => item.noForCol !== true && item.isShow !== false)
    },
  },
  mounted() {
    this.$refs.taskBomTree.init()
    this.init()
  },
  methods: {
    // 列筛选回调
    handleFilterChange(filters) {
      this.sortData = {}
      this.$refs.tableNode.clearSort()
      let filterParams = this.$filterParams(this.tableColConfig, filters)
      Object.assign(this.searchData, filterParams.search)
      Object.assign(this.sortData, filterParams.order)
      this.init()
    },
    // 选择树形节点
    selectNode(taskNumber, workorderIds) {
      this.$refs.mesSearch.clean()
      this.searchData = {}
      this.sortData = {}
      this.taskNumber = taskNumber
      this.workorderIds = workorderIds
      this.init()
    },
    // 刷新
    refresh() {
      this.$refs.mesSearch.clean()
      this.$refs.tableNode.clearSort()
      // this.$refs.nTableNode.clearSort()
      this.sortData = {}
      this.searchData = {}
      this.taskNumber = ''
      this.workorderIds = []
      this.$refs.taskBomTree.init()
      this.init()
    },
    // 初始化工单列表方法
    init(page) {
      this.isLoading1 = true
      let postData = {
        method: 'post',
        url: 'a/workorder/workorder/list',
        data: {
          pageNo: page ? page.pageNo : 1,
          pageSize: page ? page.pageSize : 5,
          query: {
            columns: this.columnList.reduce((pre, cur) => [...pre, cur.prop], []),
            ...this.searchData,
            viewSource: 5
          }
        },
        module: 'workOrderExpendTime',
        state: 'listData'
      }
      if (Object.keys(this.searchData).length > 0) {
        if (!postData.data.query.workorderProcessStatusId) {
          postData.data.query.workorderProcessStatusId = this.processStatusIds
        }
      } else {
        postData.data.query.workorderProcessStatusId = this.processStatusIds
      }
      if (Object.keys(this.sortData).length > 0) {
        postData.data.sort = this.sortData
      }
      if (this.taskNumber) {
        postData.data.query.taskNumber = this.taskNumber
      }
      if (this.workorderIds.length) {
        postData.data.query.id = this.workorderIds.toString()
      }
      this.$store.dispatch('saveData', postData).then((res) => {
        if (Object.keys(this.searchData).length > 0) {
          this.searchResult = res.count
        } else {
          this.searchResult = NaN
        }
      }).finally(() => {
        this.isLoading1 = false
      })
    },
    // 周转批次查询列表
    turnoverList(page) {
      this.isLoading = true
      let postData = {
        method: 'post',
        url: 'a/turnoverbatch/turnoverBatch/turnoverbatchexpendtime',
        module: 'workOrderExpendTime',
        data: {
          pageNo: page ? page.pageNo : 1,
          pageSize: page ? page.pageSize : 15,
          query: {
            workorderId: this.turnoverId
          }
        },
        state: 'turnoverData'
      }
      this.$store.dispatch('saveData', postData).then(() => {
        this.isLoading = false
      }).finally(() => {
        this.$nextTick(() => {
          this.$refs.nTableNode.doLayout()
        })
      })
    },
    // 查询
    _info(data) {
      this.searchData = data
      this.init()
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
    // 多选表格数据
    handleSelectionChange(val) {
      this.selectData = val
      this.turnoverId = this.selectData.reduce((pre, cur) => [...pre, cur.id], []).join(',')
      if (this.selectData.length >= 1) {
        this.turnoverList()
      }
    }
  }
}
</script>

<style scoped lang="less">
  .work_order_expend_time {
    height: 100%
  }

  .batch_list_detail {
    .pagination {
      padding-left: 0 !important;
    }
  }
</style>
<style lang="less">
  tbody {
    .fontColor .cell {
      color: #f00;
    }
  }

  .batch_list_detail {
    .el-pagination.is-background {
      padding-left: 0 !important;

      button.btn-prev {
        margin-left: 0 !important;
      }
    }
  }
</style>
